package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"tik-tok-repo/cache"
	"tik-tok-repo/modler"
	"tik-tok-repo/pkg"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "UserLogin" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	var user modler.User
	err := modler.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func UserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := modler.UserRole{

		Uid: uid,
		Rid: rid,
	}
	modler.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := modler.RoleNode{

		Rid: rid,
		Nid: nid,
	}
	modler.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	var list []modler.Role
	modler.DB.Table("roles").
		Where("user_roles.uid=?", uid).
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Debug().
		Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}

func RoleList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/
	var list []modler.Node
	modler.DB.Table("nodes").
		Where("role_nodes.rid=?", rid).
		Joins(" LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Debug().
		Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}

func HouseAdd(c *gin.Context) {
	houseCode := c.PostForm("houseCode")
	houseName := c.PostForm("houseName")
	houseSum := c.PostForm("houseSum")
	data := modler.House{

		HouseCode: houseCode,
		HouseName: houseName,
		HouseSum:  houseSum,
	}
	modler.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func HouseOrderAdd(c *gin.Context) {
	houseOrderCode := c.PostForm("houseOrderCode")
	houseOrderName := c.PostForm("houseOrderName")
	houseOrderNum := c.PostForm("houseOrderNum")
	houseOrderPrince := c.PostForm("houseOrderPrince")
	hid, _ := strconv.Atoi(c.PostForm("hid"))

	data := modler.HouseOrder{

		HouseOrderCode:   houseOrderCode,
		HouseOrderName:   houseOrderName,
		HouseOrderNum:    houseOrderNum,
		HouseOrderPrince: houseOrderPrince,
		Hid:              hid,
	}
	modler.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func HouseList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "2"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var count int64
	modler.DB.Model(&modler.HouseOrder{}).Count(&count)
	/*
		    SELECT
			  house_orders.id AS OrderId,
			  houses.house_code AS HouseCode,
			  houses.house_name AS HouseName,
			  houses.house_sum AS HouseSum,
			  house_orders.house_order_code AS HouseOrderCode,
			  house_orders.house_order_name AS HouseOrderName,
			  house_orders.house_order_num AS HouseOrderNum,
			  house_orders.house_order_prince AS HouseOrderPrince
			FROM
			  house_orders
			  LEFT JOIN houses ON houses.id = house_orders.hid
	*/

	var list []modler.HouseOrderList
	redis_key := "HouseList" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Table(" house_orders").
			Select(

				"house_orders.id AS OrderId",
				"houses.house_code AS HouseCode",
				"houses.house_name AS HouseName",
				"houses.house_sum AS HouseSum",
				"house_orders.house_order_code AS HouseOrderCode",
				"house_orders.house_order_name AS HouseOrderName",
				"house_orders.house_order_num AS HouseOrderNum",
				"house_orders.house_order_prince AS HouseOrderPrince",
			).
			Joins(" LEFT JOIN houses ON houses.id = house_orders.hid").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})
	return

}

func HouseDetail(c *gin.Context) {
	id := c.Query("id")
	var list modler.HouseOrderList
	redis_key := "HouseDetail" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Table(" house_orders").
			Select(

				"house_orders.id AS OrderId",
				"houses.house_code AS HouseCode",
				"houses.house_name AS HouseName",
				"houses.house_sum AS HouseSum",
				"house_orders.house_order_code AS HouseOrderCode",
				"house_orders.house_order_name AS HouseOrderName",
				"house_orders.house_order_num AS HouseOrderNum",
				"house_orders.house_order_prince AS HouseOrderPrince",
			).
			Joins(" LEFT JOIN houses ON houses.id = house_orders.hid").
			Where("house_orders.id=?", id).
			Debug().
			Find(&list)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
